<?php

namespace App\Http\Controllers;

use App\Utils\RetUtil;
use App\Utils\WeChatMessageUtil;
use App\Utils\WechatUtils;
use Illuminate\Http\Request;

class WeChatMessageController extends Controller
{
    //


    /**
     * 介绍 ：接受 微信发来的消息
     *
     * @Time 2020/9/21 17:16
     * @User  Mr.w
     * @param mixed ${arg1}
     */
    public function wx(Request $request)
    {
        $we_chat = new WeChatMessageController();
        $echostr = $request->get('echostr');
        //判断是验证信息还是推送信息
        if ($echostr != null) {
            $we_chat->wxCertification($request);
        }
        $data = $we_chat->wxMessage($request);
        return $data;
    }

    /**
     * 获取jssdk签名
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSignature(Request $request)
    {
        //随机字符串
        $str = time() . rand(111111, 999999) . 'suibian';
        $nonce_str = substr(md5($str), 5, 8);
        $timestamp = time(); //当前时间戳
        $url = $request->get('url');  //需要前端传过来
        $wx = new WechatUtils();

        $data = [
            'jsapi_ticket' => $wx->getJsapiTicket(),
            'noncestr' => $nonce_str,
            'timestamp' => $timestamp,
            'url' => $url
        ];

        $param = "";
        foreach ($data as $k => $v) {
            $param .= $k . '=' . $v . '&';
        }
        $p = rtrim($param, '&');
        //计算签名
        $signature = sha1($p);
//        $response['nonce_str'] = $nonce_str;
//        $response['timestamp'] = $timestamp;
//        $response['signature'] = $signature;
//        $response['url'] = $url;
        $ret = [
            'appId' => $wx->app_id,
            'nonceStr' => $nonce_str,
            'timestamp' => $timestamp,
            'signature' => $signature,
            'url' => $url
        ];
        info("url=>" . $url . " 时间戳=>" . $timestamp . " 随机数=>" . $nonce_str . " sign值=>" . $signature);
        return RetUtil::success($ret);

    }

    /**
     * 类的介绍 ：微信认证接入
     *
     * @Time 2020/8/24 12:24
     * @User  Mr.w
     * @param Request $request
     */
    private function wxCertification(Request $request)
    {
        $signature = $request->get("signature");
        $timestamp = $request->get("timestamp");
        $nonce = $request->get("nonce");
        $echostr = $request->get('echostr');
        $token = 'Xy123456';
//        info($request."wxCertification");
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
//        info($tmpStr);
//        info($echostr);
        if ($tmpStr == $signature) {
            echo $echostr;
            exit;
        }
    }

    /**
     * 类的介绍 ：微信消息接受处理
     *
     * @Time 2020/8/25 16:13
     * @User  Mr.w
     * @param Request $request
     */
    private function wxMessage(Request $request)
    {
        $xml = file_get_contents('php://input');
//        info('接受到的Xml=>' . $xml);
        //将XML数据解析为一个对象
        $xml_obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        //获取消息类型
        $RX_TYPE = trim($xml_obj->MsgType);
        $msg = '未知消息类型!';
        switch ($RX_TYPE) {
            case 'event':
                $msg = $this->receiveEvent($xml_obj);
                break;
            case 'text':
                $msg = $this->receiveText($xml_obj);
                break;
            default:
                $msg = "";

        }
        return $msg;

    }


    /**
     * 接收事件消息
     * @param $object
     */
    private function receiveEvent($object)
    {
        switch ($object->Event) {
            //关注公众号事件
            case 'subscribe':
                info('用户关注了微信公众号=>' . $object->FromUserName);
                $content = "欢迎我们";
                $desc = '点击领取商品回馈红包';
                $piurl = 'http://process.xykj.site/res/process-logo.png';
                $url = config('app.wx.home_url');
                return WeChatMessageUtil::transmitNews($object, $content, $desc, $piurl, $url);
            case 'CLICK' :
                info('用户点击了问题反馈=>' . $object->FromUserName);
                $content = "在公众号留下您的意见和问题\n或添加客服微信：13476722550";
                return WeChatMessageUtil::transmitText($object, $content);
            case 'unsubscribe':
                $content = "";
                info('用户取消关注=>' . $object->FromUserName);
                break;

            default:
                $content = "";
                break;
        }
        return WeChatMessageUtil::transmitText($object, $content);
    }


    /**
     * 类的介绍 ：接受文字消息处理
     *
     * @Time 2020/9/16 15:30
     * @User  Mr.w
     * @param mixed ${arg1}
     */
    private function receiveText($object)
    {
        return WeChatMessageUtil::transmitText($object, "客服会在24小时内联系您！");
    }

    /**
     * 回复文本消息
     * @param $object
     * @param $content
     * @return array
     */
    private function transmitText($object, $content)
    {
        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime><![CDATA[%s]]></CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[%s]]></Content>
</xml>";
        return sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);


    }

    /**
     * 回复图文消息
     * @param $object
     * @param $title
     * @param $desc
     * @param $piurl
     * @param $url
     * @return string
     */
    private function transmitNews($object, $title, $desc, $piurl, $url)
    {
        $xmlTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>![CDATA[%s]]</CreateTime>
                <MsgType><![CDATA[news]]></MsgType>
                <ArticleCount>1</ArticleCount>
                <Articles>
                <item>
                <Title><![CDATA[%s]]></Title>
                <Description><![CDATA[%s]]></Description>
                <PicUrl><![CDATA[%s]]></PicUrl>
                <Url><![CDATA[%s]]></Url>
                </item>
                </Articles>
                </xml>";
        return sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $title, $desc, $piurl, $url);
    }


}
